package com.dfa.nypl.tellafriend;

import com.dfa.nypl.common.Constants;
import com.dfa.nypl.common.EmailValidator;
import com.dfa.nypl.common.WebService;
import com.dfa.nypl.home.Home;
import com.dfa.nypl.main.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class TellAFriend extends Activity implements Constants {
	Handler mHandler = new Handler();

	private Button mSubmitButton, mCancelButton;
	private TextView mFirstNameTV, mLastNameTV, mEmailTV, mReceiveEmailTV,
			mSubjectTV, mPersionMsgTV;
	StringBuilder msgBuilder = new StringBuilder();
	private String firstNameString, lastNameString, emailString,
			receiveEmailString, subjectString, persionMsgString;

	private TelephonyManager telephonyManager;
	private WakeLock lock;
	private ConnectivityManager connectivityManager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.tell_a_friend);

		connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

		telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

		initWakeLock();

		mSubmitButton = (Button) findViewById(R.id.friend_submit_button);
		mCancelButton = (Button) findViewById(R.id.friend_cancel_button);

		mFirstNameTV = (TextView) findViewById(R.id.friend_first_name);
		mLastNameTV = (TextView) findViewById(R.id.friend_last_name);
		mEmailTV = (TextView) findViewById(R.id.friend_email);
		mReceiveEmailTV = (TextView) findViewById(R.id.friend_send_to_mail);
		mSubjectTV = (TextView) findViewById(R.id.friend_subject);
		mPersionMsgTV = (TextView) findViewById(R.id.friend_persionLize_message);

		mCancelButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				resetForm();
			}
		});

		mSubmitButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (validForm()) {
					// insert data
					firstNameString = mFirstNameTV.getText().toString().trim();
					lastNameString = mLastNameTV.getText().toString().trim();
					emailString = mEmailTV.getText().toString().trim();
					receiveEmailString = mReceiveEmailTV.getText().toString()
							.trim();
					subjectString = mSubjectTV.getText().toString().trim();
					persionMsgString = mPersionMsgTV.getText().toString()
							.trim();
					if (isConnected()) {
						// call webservice to insert data
						new InsertDataTask().execute();
					} else {
						Toast
								.makeText(TellAFriend.this, "Network unable to connect",
										Toast.LENGTH_SHORT).show();
					}

				} else {
					showAlertVaildateMessage(msgBuilder.toString());
				}

			}
		});

	}

	@Override
	protected void onPause() {
		super.onPause();
		lock.release();
	}

	@Override
	protected void onResume() {
		super.onResume();
		lock.acquire();

	}

	private void initWakeLock() {
		PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
		lock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK
				| PowerManager.ON_AFTER_RELEASE, "LiveGPSTraking");
	}

	private boolean isConnected() {
		if (telephonyManager == null || connectivityManager == null) {
			return false;
		}

		final boolean roaming = telephonyManager.isNetworkRoaming();
		final NetworkInfo info = connectivityManager.getActiveNetworkInfo();

		return info != null && info.isConnected() && !roaming;
	}

	private void resetForm() {
		mFirstNameTV.setText("");
		mLastNameTV.setText("");
		mEmailTV.setText("");
		mReceiveEmailTV.setText("");
		mSubjectTV.setText("Fund the Future");
		mPersionMsgTV.setText("");
	}

	private boolean validForm() {
		EmailValidator emailValid = new EmailValidator();

		msgBuilder.setLength(0);
		if (mFirstNameTV.getText().toString() == null
				|| mFirstNameTV.getText().toString().equals("")) {
			msgBuilder.append("- Please enter first name \n");
		}
		if (mLastNameTV.getText().toString() == null
				|| mLastNameTV.getText().toString().equals("")) {
			msgBuilder.append("- Please enter last name \n");
		}
		if (mEmailTV.getText().toString() == null
				|| mEmailTV.getText().toString().equals("")) {
			msgBuilder.append("- Please enter a valid email \n");
		} else if (!emailValid.validate(mEmailTV.getText().toString().trim())) {
			msgBuilder.append("- Please enter a valid email \n");
		}
		if (mReceiveEmailTV.getText().toString() == null
				|| mReceiveEmailTV.getText().toString().equals("")) {
			msgBuilder.append("- Please enter a valid friend's email \n");
		} else if (!emailValid.validate(mReceiveEmailTV.getText().toString()
				.trim())) {
			msgBuilder.append("- Please enter a valid friend's email \n");
		}
		if (mSubjectTV.getText().toString() == null
				|| mSubjectTV.getText().toString().equals("")) {
			msgBuilder.append("- Please enter Subject \n");
		}
		if (mPersionMsgTV.getText().toString() == null
				|| mPersionMsgTV.getText().toString().equals("")) {
			msgBuilder.append("- Please enter Persionlize your message \n");
		}

		return ((msgBuilder != null && msgBuilder.length() > 0) ? false : true);
	}

	private void showAlertVaildateMessage(String message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(TellAFriend.this);
		builder.setMessage(message).setTitle("Please enter valid data...")
				.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface d, int which) {
						d.dismiss();
					}
				});
		builder.create().show();
	}

	private class InsertDataTask extends AsyncTask<Void, Void, Void> {
		ProgressDialog dialog;
		String response = null;

		public InsertDataTask() {
			dialog = new ProgressDialog(TellAFriend.this);
			dialog.setMessage("Inserting...");
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			if (dialog.isShowing()) {
				dialog.dismiss();
			}
			if (response != null) {
				if (response.indexOf("faultcode") != -1) {
					Toast.makeText(TellAFriend.this,
							"Error when send message !", Toast.LENGTH_SHORT)
							.show();
				} else {
					// reset form
					resetForm();
					// show message
					Toast.makeText(TellAFriend.this,
							"You send message successfull !",
							Toast.LENGTH_SHORT).show();

				}

			} else {
				Toast.makeText(TellAFriend.this, "Error when send message !",
						Toast.LENGTH_SHORT).show();
			}
		}

		@Override
		protected void onPreExecute() {
			dialog.show();
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// call webservice
			response = WebService.getSingletonService().createNYPLTellAFriend(
					emailString, persionMsgString, firstNameString,
					lastNameString, receiveEmailString);
			System.out.println(">>" + response);

			return null;
		}

	}

}
